package prod_line

import "github.com/lishimeng/app-starter/stream"

type ProductionLinePacketProcessor struct {
	callback func(p []byte)
}

func NewPacketProcessor() (pp stream.PacketProcessor) {

	ppp := &ProductionLinePacketProcessor{}
	pp = ppp
	return
}

func (ppp *ProductionLinePacketProcessor) Data(payload []byte) (n int) {
	if len(payload) < 4 { // 不足一个报文长度
		return
	}
	var from = 0
	var to = -1
	for {
		packet, find := ppp.findPacket(payload[from:])
		if !find {
			break
		}
		to = from + len(packet)
		size := ppp.handlePacket(payload, from, to)
		n = n + size
		from = to
	}

	return
}

func (ppp *ProductionLinePacketProcessor) findPacket(payload []byte) (packet []byte, find bool) {
	if len(payload) < 4 { // 不足一个报文长度
		find = false
		return
	}
	_, ok := cmdMap[payload[0]]
	if !ok {
		find = false
		return // TODO 消耗一个字节或panic
	}
	size := int(payload[1])

	packet = payload[:2+size+1]
	find = true
	return
}

func (ppp *ProductionLinePacketProcessor) handlePacket(data []byte, from, to int) (size int) {

	packet := data[from:to]
	size = len(packet)
	if ppp.callback != nil {
		ppp.callback(packet)
	}
	return
}

func (ppp *ProductionLinePacketProcessor) Listen(onPacket func(p []byte)) {
	ppp.callback = onPacket
	return
}
